//
//  RequestManager.m
//  DaYing
//
//  Created by DaYing  on 2023.
//  Copyright © 2023 DaYing . All rights reserved.
//

#import "RequestManager.h"
#import <MJExtension/MJExtension.h>

@interface RequestManager ()

@property (nonatomic) AFHTTPSessionManager *managementSessionManager;//打点

@end

@implementation RequestManager

+ (instancetype)sharedInstance {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        
    });
    return instance;
}

#pragma mark - 配置请求底层参数

//打点
- (AFHTTPSessionManager *)managementSessionManager {
    if (!_managementSessionManager) {
        //主Url 可以封装起来统一管理,也可以直接写在GET参数里单独管理
        NSURL *baseUrl = [NSURL URLWithString:kManagementBaseUrl];
        //AFHTTPSessionManager 创建一个网络请求
        _managementSessionManager = [[AFHTTPSessionManager manager] initWithBaseURL:baseUrl];
        _managementSessionManager.securityPolicy.allowInvalidCertificates = YES;
        _managementSessionManager.securityPolicy.validatesDomainName = NO;
        //Requests 请求Header参数
        _managementSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [_managementSessionManager.requestSerializer setValue:@"multipart/form-data; boundary=FormBoundary" forHTTPHeaderField:@"Content-Type"];
        _managementSessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _managementSessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    }
    return _managementSessionManager;
}

#pragma mark - 接口请求

//打点
- (void)saveRequestWithKey:(NSString *)key success:(void (^)(id responseObject))success failure:(void (^)(NSString *errorMsg))failure {
    
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirst"] boolValue]) {
        return;
    }

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *time = [formatter stringFromDate:[NSDate date]];
    
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];

    [params setValue:kAppDelegate.getWorkspaceName forKey:@"sub_type"];
    [params setValue:kSafeString(kUserManager.userManager.ua) forKey:@"remark"];
    [params setValue:@"ios" forKey:@"source"];
    [params setValue:@"/" forKey:@"uid"];
    [params setValue:localVersion forKey:@"version"];
    [params setValue:kSafeString(key) forKey:@"key"];
    [params setValue:kSafeString(time) forKey:@"event_time"];
 
    [params setValue:@"jsj3" forKey:@"husds"];
    [params setValue:@"9hnj" forKey:@"qasho"];
    [params setValue:@"yoo9" forKey:@"sdq7"];
    
    [self.managementSessionManager POST:@"save.php" parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [params.allKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData *data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
            [formData appendPartWithFormData:data name:key];
        }];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"--------%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSInteger code = [dic[@"code"] integerValue];
            NSString *message = dic[@"message"];
            id data = dic[@"data"];
            if (code == 200) {
                success(data);
            } else {
                if (failure) {
                    failure(message);
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (failure) {
            failure(error.domain);
        }
    }];
}

@end
